﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Lcygcc.Infrastructure.Repository
{
    [Serializable]
    public class BaseEntity
    {
        [SugarColumn(IsIgnore = true)]
        public bool DbResult
        {
            get;
            set;
        }
        public BaseEntity()
        {
            this.DbResult = false;
        }
        public void UpdateModel(BaseEntity updateBaseEntity)
        {
            if (this.GetType() == updateBaseEntity.GetType())
            {
                PropertyInfo[] properties = this.GetType().GetProperties();
                PropertyInfo[] array = properties;
                for (int i = 0; i < array.Length; i++)
                {
                    PropertyInfo propertyInfo = array[i];
                    object value = propertyInfo.GetValue(this, null);
                    object @default = BaseEntity.GetDefault(propertyInfo.PropertyType);
                    if (value != null)
                    {
                        if (propertyInfo.PropertyType.IsValueType)
                        {
                            if (Convert.ToInt64(value) != Convert.ToInt64(@default))
                            {
                                propertyInfo.SetValue(updateBaseEntity, value, null);
                            }
                        }
                        else
                        {
                            if (!value.Equals(@default))
                            {
                                propertyInfo.SetValue(updateBaseEntity, value, null);
                            }
                        }
                    }
                    else
                    {
                        if (value != @default)
                        {
                            propertyInfo.SetValue(updateBaseEntity, value, null);
                        }
                    }
                }
            }
        }
        public static object GetDefault(Type type)
        {
            object result;
            if (type.IsValueType)
            {
                if (type.Name.Contains("Nullable"))
                {
                    result = Activator.CreateInstance(type);
                }
                else
                {
                    result = -1;
                }
            }
            else
            {
                result = null;
            }
            return result;
        }
    }
}
